#include <QDir>
#include <QDomDocument>
#include <QDomNodeList>
#include <QApplication>

#include "configxmlparser.h"
#include "defines.h"
#include "generatordata.h"

ConfigXmlParser::ConfigXmlParser(GeneratorOutputView &outputView, GeneratorData &generatorData) :
        m_outputView(outputView), m_generatorData(generatorData)
{
}

void ConfigXmlParser::handleNode(const QDomElement &element, const QString &keyPrefix)
{
    if(element.tagName().isEmpty())
        return;

    QMap<QString, QString> &configXmlData = m_generatorData.configXmlData();

    QString key = keyPrefix.isEmpty() ? element.tagName() : keyPrefix+"."+element.tagName();

    for(int i = 0; i < element.attributes().count(); i++) {
        QDomNode attrNode = element.attributes().item(i);
        configXmlData.insert(key + ":" + attrNode.toAttr().name(), attrNode.toAttr().value());
    }

    if(element.tagName() != W3C_ROOT_TAG && !element.text().isEmpty())
        configXmlData.insert(key + ":", element.text().trimmed());
}

void ConfigXmlParser::handleChildNodes(const QDomElement &element, const QString &keyPrefix)
{
    QDomNodeList childNodes = element.childNodes();
    for(int i = 0; i < childNodes.count(); i++) {
        handleNode(childNodes.at(i).toElement(), keyPrefix);
        if(childNodes.at(i).hasChildNodes()) {
            handleChildNodes(childNodes.at(i).toElement(), keyPrefix+"."+childNodes.at(i).toElement().tagName());
        }
    }
}

bool ConfigXmlParser::parse()
{
	QString widgetDirectory = m_generatorData.widgetDirectory();
    QDir dir(widgetDirectory);

    // read in config.xml
    QFile configXmlFile(dir.filePath(W3C_CONFIG_FILE));

    if(!configXmlFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QString errMsg = QString(ERR_FILE_OPEN_READ_FAILED_CANNOT_CONTINUE).arg(W3C_CONFIG_FILE);
        m_outputView.printOutput(errMsg);
        return false;
    }

    QDomDocument configXmlDocument;
    if(!configXmlDocument.setContent(&configXmlFile)) {
        QString errMsg = QString(ERR_FILE_PARSING_FAILED_CANNOT_CONTINUE).arg(W3C_CONFIG_FILE);
        m_outputView.printOutput(errMsg);
        configXmlFile.close();
        return false;
    }

    QDomElement element = configXmlDocument.firstChildElement(W3C_ROOT_TAG);

    if(element.isNull()) {
        QString errMsg = QString(ERR_WIDGET_TAG_NOT_FOUND_CANNOT_CONTINUE);
        m_outputView.printOutput(errMsg);
        return false;
    }

    handleNode(element, "");
    handleChildNodes(element, W3C_ROOT_TAG);

    /*
	QMap<QString, QString> &configXmlData = m_generatorData.configXmlData();
	foreach(const QString &key, configXmlData.keys())
        m_outputView.printOutput(key + ": " + configXmlData.find(key).value());
	*/
    return true;
}
